package com.tyj.movie.config.security;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tyj.movie.entity.Admin;
import com.tyj.movie.mapper.AdminMapper;
import com.tyj.movie.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 日期: 2021/6/7 10:50
 * 作者: 谭友杰
 * 类说明:
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    AdminMapper adminMapper;

    /**
     * 注意 只会调用一次
     * @param name 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        //验证账号
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",name));

        if (admin==null){
            throw new RuntimeException("账号不存在");
        }

        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();

        //查询当前角色
//        List<RoleEntity> roles = roleDao.selectRole(userEntity.getId());

        //查询当前权限
//        List<AuthEntity> auths = authDao.selectAuth(roles);
//        for (RoleEntity role : roles) {
//            String roleName = "ROLE_" + role.getRoleName();
//            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
//            grantedAuthorities.add(simpleGrantedAuthority);
//        }
//        for (AuthEntity auth : auths) {
//            if (auth.getUrl()!="" || auth.getUrl()!=null){
//                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(auth.getAuth());
//                grantedAuthorities.add(simpleGrantedAuthority);
//            }
//        }


        //获得当前权限能访问的请求
//        List<AuthEntity> authEntities=authService.packingAuthData(auths);
//        userEntity.setAuthEntities(authEntities);

        UserDetails userDetails= new User(admin.getUsername(),admin.getPassword(),grantedAuthorities);

        return userDetails;
    }

}
